<template src="./template.html"></template>

<script>
/* global moment */
import apiUrls from 'common/api-urls'
import ResizeMixin from 'mixins/resize'
import { PAGE_CONFIG, ORDER_SORTS } from 'common/consts';
import { COL_INDEXS, PUBLIST_STATUS } from './consts';
import { getCourse, delCourse } from './models';

import addDialog from './add-dialog.vue'

export default {
  components: { addDialog },
  mixins: [ResizeMixin],
  data() {
    return {
      enUrl: apiUrls.enUrl, // 地址
      COL_INDEXS,
      PUBLIST_STATUS,
      isPageLoading: false,

      tableList: [],
      PAGE_CONFIG: PAGE_CONFIG,
      pageNo: PAGE_CONFIG.defaultPageNo,
      pageSize: PAGE_CONFIG.defaultPageSize,
      totalCount: 0,
      filterForm: {
        q: ''
      },

      editDialogVisible: false,
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo
    }
  },

  methods: {
    $sortChange({ column, prop, order }) {
      console.log(column, prop, order)
      const orderIdx = this.filterForm.orders.findIndex(it => it.column === prop)
      const params = {
        column: prop,
        order: ORDER_SORTS[order]
      }
      if (orderIdx <= -1) {
        if (order) {
          this.filterForm.orders.push(params)
        }
      } else {
        if (order) {
          this.$set(this.filterForm.orders, orderIdx, params)
        } else {
          this.filterForm.orders.splice(orderIdx, 1)
        }
      }
      this.$getTableList()
    },
    barFormat(percentage) {
      return percentage === 100 ? '满' : `${percentage}%`;
    },
    $search() {
      this.pageNo = 1
      this.$getTableList()
    },
    // 删除请求
    async $handleDeleteHttp(params) {
      try {
        this.isLoading = true
        await delCourse(params)
        this.$message.success('删除成功')
        // if (this.tableData.length === 1) {
        //   this.pageNo = this.pageNo > 1 ? this.pageNo - 1 : this.pageNo
        // }
        this.$search()
      } catch (err) {
        this.isLoading = false
        this.$message.error(err.retDesc || err.message || '删除出错')
      }
    },
    // 删除点击
    $handleDelete(row) {
      const params = {
        id: row.id
      }
      this.$confirm('是否确认删除该课程？', {
        type: 'warning',
        confirmButtonText: '删除',
      }).then(() => {
        this.$handleDeleteHttp(params)
      }).catch(() => {
        console.log('取消');
      });
    },
    $handleEdit(row) {
      this.$router.push(`/curriculum/manager/info/${row.id}`)
    },
    $handlePeriod(row) {
      this.$router.push({
        name: 'curriculum.manager.lesson-period',
        params: {
          id: row.id
        }
      })
    },
    $handleTrainee(row) {
      this.$router.push({
        name: 'curriculum.manager.trainee',
        params: {
          id: row.id
        }
      })
    },
    $handleLessonData(row) {
      this.$router.push({
        name: 'curriculum.manager.lesson-data',
        params: {
          id: row.id
        }
      })
    },
    async $getTableList() {
      this.isPageLoading = true;
      const params = {
        ...this.filterForm,
        limit: this.pageSize,
        page: this.pageNo,
        orderType: 'desc'
      };

      try {
        const { data } = await getCourse(params);
        this.tableList = (data.list || []).map(item => {
          let deadlineTime = '永久'
          if (parseInt(item.isLimitTime, 10) !== 0) {
            deadlineTime = moment(item.deadline).format('YYYY-MM-DD HH:mm')
            if (parseInt(item.isPublish, 10) === 1) {
              const currTime = moment().valueOf()
              const deadTime = moment(item.deadline).valueOf()
              if (currTime > deadTime) {
                deadlineTime = '已截止'
              }
            }
          }
          return {
            ...item,
            deadlineTime: deadlineTime,
            numProcess: item.studentNum ? parseInt((item.hasFinishStuNum / item.studentNum) * 100, 10) : 0
          }
        })
        this.totalCount = data.total
        this.isPageLoading = false;
      } catch (err) {
        this.isPageLoading = false;
        this.$message.error(err.message || '获取课程列表异常')
      }
    },
    $handlePageChange() {
      this.$getTableList();
    },
    $addSuccess(data, cb) {
      if (data && data.id) {
        this.$handleEdit({ id: data.id })
      } else {
        this.$search()
      }
      this.editDialogVisible = false
      if (cb) {
        cb()
      }
    }
  },
  created() {
    this.$getTableList();
  },
};
</script>
